<template>
  <div class="user-product-stats">
    <a-row :gutter="[16, 16]">
      <a-col :span="24">
        <a-card>
          <template #title>
            <div class="card-title">
              <bar-chart-outlined/>
              <span>商品发布统计</span>
            </div>
          </template>
          <template #extra>
            <a-radio-group v-model:value="timeRange" button-style="solid">
              <a-radio-button value="7">近7天</a-radio-button>
              <a-radio-button value="30">近30天</a-radio-button>
              <a-radio-button value="90">近90天</a-radio-button>
            </a-radio-group>
          </template>
          <v-chart class="chart" :option="chartOption" autoresize/>
        </a-card>
      </a-col>
    </a-row>
    <a-row :gutter="[16, 16]" style="margin-top: 16px;">
      <a-col :span="6">
        <a-card>
          <statistic
              title="总记录数"
              :value="totalRecords"
              :value-style="{ color: '#722ed1' }"
          >
            <template #prefix>
              <file-outlined/>
            </template>
          </statistic>
        </a-card>
      </a-col>
      <a-col :span="6">
        <a-card>
          <statistic
              title="总发布商品"
              :value="totalProducts"
              :value-style="{ color: '#4053cc' }"
          >
            <template #prefix>
              <shopping-outlined/>
            </template>
          </statistic>
        </a-card>
      </a-col>
      <a-col :span="6">
        <a-card>
          <statistic
              title="平均日发布"
              :value="averageDaily"
              :precision="2"
              :value-style="{ color: '#cf1322' }"
          >
            <template #prefix>
              <rise-outlined/>
            </template>
          </statistic>
        </a-card>
      </a-col>
      <a-col :span="6">
        <a-card>
          <statistic
              title="最高单日发布"
              :value="maxDaily"
              :value-style="{ color: '#1890ff' }"
          >
            <template #prefix>
              <trophy-outlined/>
            </template>
          </statistic>
        </a-card>
      </a-col>
    </a-row>
  </div>
</template>

<script setup>
import {ref, computed, watch, onMounted, reactive} from 'vue';
import {BarChartOutlined, ShoppingOutlined, RiseOutlined, TrophyOutlined, FileOutlined} from '@ant-design/icons-vue';
import {Statistic} from 'ant-design-vue';
import VChart from 'vue-echarts';
import {use} from 'echarts/core';
import {CanvasRenderer} from 'echarts/renderers';
import {BarChart} from 'echarts/charts';
import {GridComponent, TooltipComponent, TitleComponent, LegendComponent, DataZoomComponent} from 'echarts/components';
import {useUserStore, useProductStore} from "@/stores/index.js";


use([
  CanvasRenderer,
  BarChart,
  GridComponent,
  TooltipComponent,
  TitleComponent,
  LegendComponent,
  DataZoomComponent
]);

const userStore = useUserStore();
const productStore = useProductStore();

const timeRange = ref('7');

const mockData = reactive({
  '7': [],
  '30': [
    {date: '2023-05-01', count: 2},
    {date: '2023-05-05', count: 5},
    {date: '2023-05-10', count: 3},
    {date: '2023-05-15', count: 7},
    {date: '2023-05-20', count: 4},
    {date: '2023-05-25', count: 6},
    {date: '2023-05-30', count: 8},
  ],
  '90': [
    {date: '2023-03-01', count: 10},
    {date: '2023-03-15', count: 15},
    {date: '2023-04-01', count: 8},
    {date: '2023-04-15', count: 12},
    {date: '2023-05-01', count: 20},
    {date: '2023-05-15', count: 18},
    {date: '2023-05-30', count: 25},
  ]
});

onMounted(async () => {
  const userId = userStore.userInfo ? userStore.userInfo.userId : null;
  if (userId) {
    const success = await productStore.fetchProducts(userId, 'chart');
    if (success) {
      mockData['7'] = JSON.parse(JSON.stringify(productStore.productStats));
    } else {
      console.log("获取商品数据失败", productStore.error);
    }
  } else {
    console.log('用户ID为空');
  }
});

const chartData = computed(() => {
  console.log('chartData updated', mockData[timeRange.value]);
  return mockData[timeRange.value];
});

const chartOption = computed(() => ({
  title: {
    text: '商品发布趋势',
    left: 'center'
  },
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'shadow'
    }
  },
  xAxis: {
    type: 'category',
    data: chartData.value.map(item => item.date),
    axisLabel: {
      rotate: 45
    }
  },
  yAxis: {
    type: 'value',
    name: '发布数量'
  },
  series: [{
    data: chartData.value.map(item => item.count),
    type: 'bar',
    itemStyle: {
      color: '#f1c5c5'
    },
    emphasis: {
      itemStyle: {
        color: '#1890ff'
      }
    }
  }],
  grid: {
    left: '3%',
    right: '4%',
    bottom: '15%',
    containLabel: true
  },
  dataZoom: [
    {
      type: 'inside',
      start: 0,
      end: 100
    },
    {
      type: 'slider',
      start: 0,
      end: 100
    }
  ]
}));

const totalProducts = computed(() => {
  return chartData.value.reduce((sum, item) => sum + item.count, 0);
});

const averageDaily = computed(() => {
  return totalProducts.value / chartData.value.length;
});

const maxDaily = computed(() => {
  return Math.max(...chartData.value.map(item => item.count));
});

const totalRecords = computed(() => {
  return Object.values(mockData).reduce((total, range) => total + range.length, 0);
});

watch(timeRange, (newValue) => {
  console.log(`Time range changed to ${newValue} days`);
  // 这里可以添加API调用来获取新的数据
});
</script>

<style scoped>
.user-product-stats {
  width: 100%;
  max-width: 1200px;
}

.card-title {
  display: flex;
  align-items: center;
  font-size: 16px;
  font-weight: bold;
}

.card-title .anticon {
  margin-right: 8px;
}

.chart {
  height: 400px;
  width: 100%;
}

:deep(.ant-card-head) {
  min-height: 48px;
}

:deep(.ant-card-head-title) {
  padding: 8px 0;
}

:deep(.ant-card-extra) {
  padding: 8px 0;
}
</style>

